package com.wpzf.zxhc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import com.wpzf.zxhc.mapper.APPWyjzMapper;
import com.wpzf.zxhc.service.APPWyjzService;
import com.wpzf.zxhc.service.XjtbTbBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class APPWyjzServiceImpl implements APPWyjzService {

    @Autowired
    private APPWyjzMapper appWyjzMapper;

    @Autowired
    private XjtbTbBaseService xjtbTbBaseService;

    @Autowired
    private TokenService tokenService;


    @Override
    public Map<String, Object> getsql(String key) {
        return appWyjzMapper.getsql(key);
    }

    @Override
    public List<Map<String, Object>> executeQuery(Map<String, Object> m) {
        return appWyjzMapper.executeQuery(m);
    }

    @Override
    public List<Map<String, Object>> queryDictionarylist(String key) {
        return appWyjzMapper.queryDictionarylist(key);
    }

    @Override
    public List<Map<String, Object>> getPageData(Map<String, Object> param) {
        return appWyjzMapper.getPageData(param);
    }

    @Override
    public List<Map<String, Object>> getPch(Map<String, Object> param) {
        return appWyjzMapper.getPch(param);
    }

    @Override
    public List<Map<String, Object>> getSheng(Map<String, Object> param) {
        return appWyjzMapper.getSheng(param);
    }

    @Override
    public List<Map<String, Object>> getShi(Map<String, Object> param) {
        return appWyjzMapper.getShi(param);
    }

    @Override
    public List<Map<String, Object>> getXian(Map<String, Object> param) {
        return appWyjzMapper.getXian(param);
    }

    @Override
    public List<Map<String, Object>> getXz(Map<String, Object> param) {
        return appWyjzMapper.getXz(param);
    }

    @Override
    public List<Map<String, Object>> getCun(Map<String, Object> param) {
        return appWyjzMapper.getCun(param);
    }

    @Override
    public Integer getPageDataCount(Map<String, Object> param) {
        return appWyjzMapper.getPageDataCount(param);
    }

    @Override
    public List<Map<String, Object>> getTaskDetails(Map<String, Object> param) {
        return appWyjzMapper.getTaskDetails(param);
    }

    @Override
    public Integer getTaskDetailsCount(Map<String, Object> param) {
        return appWyjzMapper.getTaskDetailsCount(param);
    }

    @Override
    public List<Map<String, Object>> queryAddDkList(Map<String, Object> param) {
        return appWyjzMapper.queryAddDkList(param);
    }

    @Override
    public Integer queryAddDkListCount(Map<String, Object> param) {
        return appWyjzMapper.queryAddDkListCount(param);
    }

    @Override
    public Integer addTaskDetails(Map<String, Object> param) {
        Integer rest = 0;
        String task_id = param.get("task_id") + "";
        appWyjzMapper.updateTaskCount(param);

        Map<String, Object> task = appWyjzMapper.queryTaskById(param);
        if (task != null) {
            // 省

            // 市
            StringBuffer city = new StringBuffer(task.get("city") + "");
            List<String> shiList = (List<String>) param.get("shi");
            for (String s : shiList) {
                if (city.indexOf(s) == -1) {
                    city.append(",");
                    city.append(s);
                }
            }
            // 县
            StringBuffer xmc = new StringBuffer(task.get("xmc") + "");
            List<String> xmcList = (List<String>) param.get("xian");
            for (String s : xmcList) {
                if (xmc.indexOf(s) == -1) {
                    xmc.append(",");
                    xmc.append(s);
                }
            }
            StringBuffer xzqdm = new StringBuffer(task.get("xzqdm") + "");
            List<String> xzqdmList = (List<String>) param.get("xzqdm");
            for (String s : xzqdmList) {
                if (xzqdm.indexOf(s) == -1) {
                    xzqdm.append(",");
                    xzqdm.append(s);
                }
            }
            // 乡镇
            StringBuffer xzmc = new StringBuffer(task.get("xzmc") + "");
            List<String> xzmcList = (List<String>) param.get("xz");
            for (String s : xzmcList) {
                if (xzmc.indexOf(s) == -1) {
                    xzmc.append(",");
                    xzmc.append(s);
                }
            }
            // 村
            StringBuffer cmc = new StringBuffer(task.get("cmc") + "");
//            List<String> cmcList = (List<String>) param.get("cun");
            String cun = param.get("cun") + "";
            if (cmc.indexOf(cun) == -1) {
                cmc.append(",");
                cmc.append(cun);
            }

            Map<String, Object> m = new HashMap<>();
            m.put("task_id", task_id);
            m.put("city", city.toString());
            m.put("xmc", xmc.toString());
            m.put("xzqdm", xzqdm.toString());
            m.put("xzmc", xzmc.toString());
            m.put("cmc", cmc.toString());
            appWyjzMapper.updateTask(m);
        }


        List<Map<String, Object>> taskdetailList = (List<Map<String, Object>>) param.get("taskdetail");

        for (Map<String, Object> map : taskdetailList) {
            map.put("task_id", task_id);
            map.put("taskdetail_id", UUID.randomUUID().toString());
            rest += appWyjzMapper.addTaskdetail(map);
        }
        return rest;
    }

    @Override
    public Integer update(Map<String, Object> param) {
        return appWyjzMapper.update(param);
    }

    @Override
    @Transactional
    public Integer del(Map<String, Object> param) {
//        appWyjzMapper.deleteTaskdetail(param);
//        appWyjzMapper.deleteTaskdetailAnnex(param);
        return appWyjzMapper.deleteTask(param);
    }

    @Override
    public List<Map<String, Object>> getDataNoAssigning(Map<String, Object> param) {
        return appWyjzMapper.getDataNoAssigning(param);
    }

    @Override
    public Integer getDataNoAssigningCount(Map<String, Object> param) {
        return appWyjzMapper.getDataNoAssigningCount(param);
    }

    @Override
    public List<Map<String, Object>> getAssignPersonnel(Map<String, Object> param) {
        List<Map<String, Object>> rest = new ArrayList<>();
        String xzqdm = param.get("xzqdm") + "";
        if (xzqdm.length() == 2) {
            if ("省".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getAdministratorsSheng(param);
            } else if ("市".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getAdministratorsShi(param);
            } else if ("县".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getAdministratorsXian(param);
            }
        } else if (xzqdm.length() == 4) {
            if ("市".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getOperatorsShi(param);
            } else if ("县".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getAdministratorsXian(param);
            }
        } else if (xzqdm.length() == 6) {
            if ("县".equals(param.get("dj") + "")) {
                rest = appWyjzMapper.getOperatorsXian(param);
            }
        }
        return rest;
    }

    @Override
    public Integer addTask(Map<String, Object> param) {
        Integer rest = 0;
        Map<String, Object> taskMap = (Map<String, Object>) param.get("task");
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        taskMap.put("createid", loginUser.getSysUser().getUserId());
        taskMap.put("creator", loginUser.getSysUser().getUserName());
        taskMap.put("createdate", null);
        String xzqdm = loginUser.getSysUser().getXzqdm();
        if (xzqdm.length() == 2) {
            taskMap.put("creator_lever", "省");
        } else if (xzqdm.length() == 4) {
            taskMap.put("creator_lever", "市");
        } else if (xzqdm.length() == 6) {
            taskMap.put("creator_lever", "县");
        }

        List<Integer> userList = (List<Integer>) taskMap.get("userList");
        for (Integer ower_user_id : userList) {
            String task_id = UUID.randomUUID().toString();
            taskMap.put("task_id", task_id);
            taskMap.put("zpry", ower_user_id);
            Integer i = appWyjzMapper.addTask(taskMap);
            if (i > 0) {
                List<Map<String, Object>> taskdetailList = (List<Map<String, Object>>) param.get("taskdetail");
                for (Map<String, Object> map : taskdetailList) {
                    map.put("task_id", task_id);
                    map.put("taskdetail_id", UUID.randomUUID().toString());
                    rest += appWyjzMapper.addTaskdetail(map);
                }
            }
        }
        return rest;
    }

    @Override
    @Transactional
    public Integer removeTask(Map<String, Object> param) {
        Integer rest = 0;
        Map<String, Object> djzTaskdetail = appWyjzMapper.queryDjzTaskdetail(param);
        if (djzTaskdetail != null) {
            rest = appWyjzMapper.removeTaskdetail(param);
            appWyjzMapper.removeTaskdetailAnnex(djzTaskdetail);
        } else {
            rest = -1;
        }
        return rest;
    }

    @Override
    public List<Map<String, Object>> querySheng(Map<String, Object> param) {
        return appWyjzMapper.querySheng(param);
    }

    @Override
    public List<Map<String, Object>> queryShi(Map<String, Object> param) {
        return appWyjzMapper.queryShi(param);
    }

    @Override
    public List<Map<String, Object>> queryXian(Map<String, Object> param) {
        return appWyjzMapper.queryXian(param);
    }

    @Override
    public List<Map<String, Object>> queryReviewUsers(Map<String, Object> param) {
        return appWyjzMapper.queryReviewUsers(param);
    }

    @Override
    public Integer queryReviewUsersCount(Map<String, Object> param) {
        return appWyjzMapper.queryReviewUsersCount(param);
    }

    @Override
    public Integer register(Map<String, Object> param) {
        Integer rest = 0;
        //查询用户名是否重复
        List<Map<String, Object>> user = appWyjzMapper.queryUserByUsername(param);
        if (user != null && user.size() > 0) {
            //用户名已存在
            return -1;
        } else {
            //保存到县级用户申请表
            param.put("submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            param.put("password", passwordEncoder.encode(param.get("password") + ""));
            rest = appWyjzMapper.saveWyUser(param);
        }
        return rest;
    }


    @Override
    @Transactional
    public Integer reviewUsers(Map<String, Object> param) {
        Integer rest = 0;
        List<Map<String, Object>> user = appWyjzMapper.queryUser(param);
        if (user != null && user.size() > 0) {
            //用户名已存在
            return -1;
        } else {
            param.put("sh_submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            rest = appWyjzMapper.updateWyXianUserState(param);
            if (rest > 0 && "1".equals(param.get("state") + "")) {
                //审核通过注册用户
                Integer user_id = appWyjzMapper.getUserId(param);
                param.put("user_id", user_id);
                appWyjzMapper.addUser(param);
                appWyjzMapper.deleteUserRoleByUserId(param);
                appWyjzMapper.deleteUserPlatformRoleByUserId(param);
                appWyjzMapper.addUserRole(param);
                appWyjzMapper.addUserPlatformRole(param);
            }
        }
        return rest;
    }

    @Override
    public List<Map<String, Object>> queryUserList(Map<String, Object> param) {
        return appWyjzMapper.queryUserList(param);
    }

    @Override
    public Integer queryUserListCount(Map<String, Object> param) {
        return appWyjzMapper.queryUserListCount(param);
    }

    @Override
    @Transactional
    public Integer deleteUser(Map<String, Object> param) {
        appWyjzMapper.deleteUserPlatformRoleByUserId(param);
        appWyjzMapper.deleteUserRoleByUserId(param);
        return appWyjzMapper.deleteUserByUserId(param);
    }

    @Override
    @Transactional
    public Integer updateUserInfo(Map<String, Object> param) {
        appWyjzMapper.updateUserPlatformRoleByUserId(param);
        appWyjzMapper.updateRoleByUserId(param);
        return appWyjzMapper.updateUserInfo(param);
    }

    @Override
    public Integer updateUserPassword(Map<String, Object> param) {
        Map<String, Object> userInfo = appWyjzMapper.getUserInfo(param);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        param.put("password", passwordEncoder.encode("ZHHC_" + userInfo.get("phonenumber") + ""));
        return appWyjzMapper.updateUserPassword(param);
    }

    @Override
    @Transactional
    public Integer addUser(Map<String, Object> param) {
        Integer rest = 0;
        List<Map<String, Object>> user = appWyjzMapper.queryUser(param);
        if (user != null && user.size() > 0) {
            //用户名已存在
            return -1;
        } else {
            param.put("sh_submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            Integer user_id = appWyjzMapper.getUserId(param);
            param.put("user_id", user_id);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            param.put("password", passwordEncoder.encode(param.get("password") + ""));
            rest = appWyjzMapper.addUser(param);
            appWyjzMapper.deleteUserRoleByUserId(param);
            appWyjzMapper.deleteUserPlatformRoleByUserId(param);
            appWyjzMapper.addUserRole(param);
            appWyjzMapper.addUserPlatformRole(param);
        }
        return rest;
    }

    @Override
    public String queryMsg(Map<String, Object> param) {
        List<String> list = appWyjzMapper.queryMsg(param);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i>0){
                sb.append("\n");
            }
            sb.append(list.get(i));
        }
        return sb.toString();
    }

    @Override
    public Integer downloadImage(Map<String, Object> param) {

        Integer rest = 0;
        List<Map<String, Object>> dkList = appWyjzMapper.queryDkList(param);

        //获取举证照片
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> dk : dkList) {
            String tbbh = dk.get("tbbh") + "";
            String xzqdm = dk.get("xzqdm") + "";
            String pch = dk.get("pch") + "";
            map.put("tbbh", tbbh);
            map.put("dkbh", tbbh);
            map.put("xzqdm", xzqdm);
            map.put("pch", pch);
            ModelMap modelMap = xjtbTbBaseService.getShowImgsnew(dk);
            String data = modelMap.get("data") + "";
            JSONArray jsonArray = JSONArray.parseArray(data);
            System.out.println(jsonArray);
            for (Object o : jsonArray) {
                Map<String, Object> m = (Map<String, Object>) o;
                if (m.get("data") != null) {
//                    System.out.println(0);
                    List<Map<String, Object>> l = (List<Map<String, Object>>) m.get("data");
                    if (l != null && l.size() > 0) {
                        for (Map<String, Object> d : l) {
                            Map<String, Object> other = (Map<String, Object>) d.get("other");
                            List<Map<String, Object>> hcfjList = (List<Map<String, Object>>) other.get("hcfj");
                            if (hcfjList != null && hcfjList.size() > 0) {
                                for (Map<String, Object> hcfj : hcfjList) {
                                    System.out.println(hcfj);
                                    String fileUrl = hcfj.get("url") + "";

                                    // 创建保存路径
                                    String savePath = System.getProperty("user.dir") + "\\" + "appFiles" + "\\" + pch + "\\" + xzqdm + "\\" + tbbh;
                                    // 保存文件的文件夹
                                    File folder = new File(savePath);
                                    // 判断路径是否存在,不存在则自动创建
                                    if (!folder.exists()) {
                                        folder.mkdirs();
                                    }

                                    //文件存到本地
                                    try {
                                        URL url = new URL(fileUrl);
                                        URLConnection connection = url.openConnection();

                                        InputStream inputStream = connection.getInputStream();

                                        // 获取文件名
                                        String fileName = getFileNameFromUrl(fileUrl);
                                        String filePath = savePath + "\\" + fileName;
                                        File targetFile = new File(savePath,fileName);
                                        if (!targetFile.exists()) {
                                            FileOutputStream outputStream = new FileOutputStream(targetFile);

                                            byte[] buffer = new byte[1024];
                                            int bytesRead;
                                            while ((bytesRead = inputStream.read(buffer))!= -1) {
                                                outputStream.write(buffer, 0, bytesRead);
                                            }

                                            outputStream.close();
                                            System.out.println("文件下载成功，保存为: " + filePath);
                                        } else {
                                            System.out.println("文件已存在，无需下载：" + filePath);
                                        }

                                        inputStream.close();
                                        //connection.disconnect();

                                        String OBSAddress = "app" + "/" + pch + "/" + xzqdm + "/" + tbbh + "/" + fileName;
                                        String log = OBSUploadUnits.OBSUpload(OBSAddress, filePath);
                                        if ("success".equals(log)) {
                                            Map<String,Object> p = new HashMap<>();
                                            p.put("dkbh",tbbh);
                                            p.put("pch",pch);
                                            p.put("xzqdm",xzqdm);
                                            p.put("tbybh",tbbh);
                                            p.put("jkbsm",null);
                                            p.put("fjmc",fileName);
                                            p.put("fjlx","Y");
                                            p.put("fj","https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress);
                                            p.put("pssj",hcfj.get("pssj"));
                                            p.put("psjd",hcfj.get("psjd"));
                                            p.put("psry",hcfj.get("psry"));
                                            p.put("longitude",hcfj.get("longitude"));
                                            p.put("latitude",hcfj.get("latitude"));
                                            p.put("xzb",hcfj.get("longitude"));
                                            p.put("yzb",hcfj.get("latitude"));
                                            p.put("jym",null);
                                            p.put("meta_record",null);
                                            p.put("psgd",hcfj.get("psgd"));
                                            p.put("psfyj",hcfj.get("psfyj"));
                                            p.put("psaltitude",hcfj.get("psaltitude"));
                                            p.put("creator",null);
                                            p.put("createdate",null);
                                            p.put("modifier",null);
                                            p.put("modifydate",null);
                                            p.put("taskdetail_id",null);
                                            p.put("project_id",null);
                                            p.put("task_id",null);
                                            p.put("uuid",UUID.randomUUID().toString());
                                            p.put("isdelete",null);
                                            p.put("json",null);
                                            p.put("id",null);
                                            p.put("modifyid",null);
                                            p.put("jcbh",null);
                                            p.put("createid",null);
                                            appWyjzMapper.addReTaskdetailAnnex(p);
                                            rest++;
                                        }
                                        deleteFolder(folder);

                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return rest;
    }

    public static void deleteFolder(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        folder.delete();
    }

    private static String getFileNameFromUrl(String fileUrl) {
        // 先从URL中获取原始文件名
        String rawFileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        // 如果文件名中包含查询参数（以?分隔），则去除查询参数部分
        int queryIndex = rawFileName.indexOf('?');
        if (queryIndex!= -1) {
            rawFileName = rawFileName.substring(0, queryIndex);
        }
        return rawFileName;
    }

}
